package it.sd.wdc.spider.repository.impl;


import it.sd.utility.XMLWrapper;
import it.sd.wdc.schema.spider.Bean;
import it.sd.wdc.schema.spider.Input;
import it.sd.wdc.schema.spider.Output;
import it.sd.wdc.schema.spider.Result;
import it.sd.wdc.schema.spider.Service;
import it.sd.wdc.schema.spider.Services;
import it.sd.wdc.schema.spider.Spider;
import it.sd.wdc.schema.spider.Step;
import it.sd.wdc.spider.repository.ScriptRepository;
import it.sd.wdc.spider.repository.WDCAbstractStep;
import it.sd.wdc.spider.repository.WDCParams;
import it.sd.wdc.spider.repository.WDCService;
import it.sd.wdc.spider.repository.WDCStep;
import it.sd.wdc.spider.repository.WDCStepResult;
import it.sd.wdc.spider.repository.WDCTemplate;
import it.sd.wdc.spider.repository.template.SpiderNodeTemplate;
import it.sd.wdc.spider.repository.template.TemplateParser;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;

import org.apache.log4j.Logger;

public class ScriptRepositoryDaoXML extends ScriptRepository {

	private String folderName;
	private String fileName;
	private String id;

	@Override
	public void load() throws Exception {

		try {
			File file = new File (folderName + File.separator + fileName);
			if (!file.exists()) {
				throw new FileNotFoundException(file.getAbsolutePath());
			}
			Spider spider = (Spider)Spider.unmarshal(new FileReader(file));
			
			loadServices(spider);
			
		} catch (Exception e) {
			throw e;
		}
	}

	private void loadServices(Spider spider) throws Exception {
		
		Services services = spider.getServices();
		if (services!=null) {
			Service[] slist = services.getService();
			if (slist!=null) {
				for (int i = 0; i < slist.length; i++) {
					Service sb = slist[i];
					WDCService service = new WDCService();
					service.setId(i+1);
					service.setDescription(sb.getDescription());
					service.setName(sb.getName());
					service.setNewData(false);
					
					loadSteps(service, sb);
					loadInputParams(service, sb);
					loadOutputParams(service, sb);
					addService(service);
				}
			}
		}

	}

	private void loadSteps(WDCService service, Service sb)  {
		Step[] steps = sb.getStep();
		if (steps!=null) {
			for (int i = 0; i < steps.length; i++) {
				Step step = steps[i];
				WDCStep wdcs = new WDCStep();
				wdcs.setAction(step.getAction());
				wdcs.setDescription(step.getDescription());
				wdcs.setHost(step.getHost());
				wdcs.setId(i+1);
				wdcs.setMethod(step.getMethod());
				wdcs.setName(step.getName());
				wdcs.setProgressivo(i+1);
				wdcs.setProtocol(step.getProtocol());
				wdcs.setTemplate(step.getTemplate());
				service.addStep(wdcs);
				
				loadTemplate(step.getTemplate());
				
				loadInputParams(wdcs, step);
				loadOutputParams(wdcs, step);
				loadResults(wdcs, step);
			}
		}
	}

	private WDCTemplate retrieveTemplate(String id)   {
		
		WDCTemplate template = null;
		FileInputStream fis = null;
		
		try {
			
			File file = new File(folderName + File.separator + id + ".xml");
			fis = new FileInputStream(file);
			XMLWrapper xml = new XMLWrapper(fis);
			template = new WDCTemplate();
			template.setXml(xml.toString());
			template.setName(id);
			
		} catch(Exception e) {
			Logger.getLogger(this.getClass()).error("Errore caricamento template" + id);
		} finally {
			try {fis.close();} catch(Exception e1) {}
		}

		return template;
	}

	private void loadTemplate(String id)   {

		try {
			addTemplate(retrieveTemplate(id));
		} catch(Exception e) {
			Logger.getLogger(this.getClass()).error("Errore caricamento template" + id);
		}
		
	}

	private void loadInputParams(WDCAbstractStep step, Bean xmlBean) {
		Input[] inputs = xmlBean.getInput();
		if (inputs!=null) {
			for (int i = 0; i < inputs.length; i++) {
				WDCParams p = new WDCParams();
				p.setName(inputs[i].getName());
				p.setValue(inputs[i].getValue());
				step.addInputParam(p);
			}
		}
	}

	private void loadOutputParams(WDCAbstractStep step, Bean xmlBean) {
		Output[] inputs = xmlBean.getOutput();
		if (inputs!=null) {
			for (int i = 0; i < inputs.length; i++) {
				WDCParams p = new WDCParams();
				p.setName(inputs[i].getName());
				p.setValue(inputs[i].getValue());
				step.addOutputParam(p);
			}
		}
	}

	private void loadResults(WDCAbstractStep step, Step xmlBean) {
		Result[] results = xmlBean.getResult();
		if (results !=null) {
			for (int i = 0; i < results .length; i++) {
				WDCStepResult p = new WDCStepResult();
				p.setCondition(results [i].getCondition());
				p.setNextStep(results [i].getNextStep());
				step.addStepResult(p);
			}
		}
	}

	public SpiderNodeTemplate getTemplateDocument(String key) {

		SpiderNodeTemplate node = null;
		
		try {
			WDCTemplate t = retrieveTemplate(key);
			if (t!=null) {
				TemplateParser tp = new TemplateParser();
				node = tp.parse(t.getXml());
			}
		} catch(Exception e) {
			Logger.getLogger(this.getClass()).error("errore template: " + key, e);
		}

		if (node==null) node = new SpiderNodeTemplate("page");

		return node;
		
	}

	public void store(WDCService service) throws Exception {

		throw new Exception("metodo non implementato");
		
	}

	public void store(WDCTemplate template) throws Exception {

		throw new Exception("metodo non implementato");
		
	}

	@Override
	public String getId() {
		return id;
	}

	/**
	 * @return the folderName
	 */
	public String getFolderName() {
		return folderName;
	}

	/**
	 * @param folderName the folderName to set
	 */
	public void setFolderName(String folderName) {
		this.folderName = folderName;
	}

	/**
	 * @return the fileName
	 */
	public String getFileName() {
		return fileName;
	}

	/**
	 * @param fileName the fileName to set
	 */
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(String id) {
		this.id = id;
	}

	
}
